package com.liyiruo.uploadfiles.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/7/8 下午4:13
 */
@Controller
@RequestMapping("upload")
@Slf4j
public class FileController {
    private static final String UPLOAD_DIR = "files";

    @RequestMapping("/file")
    @ResponseBody
    public String uploadFiles(@RequestParam("file") MultipartFile[] files,
                              RedirectAttributes redirectAttributes) {

        log.info("===>{}","file");
        List<String> fileNames = new ArrayList<>();

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; // 跳过空文件
            }
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOAD_DIR + File.separator+ file.getOriginalFilename());

                //---------
                //如果文件不存在，应该先创建
                Path parentDir = path.getParent();
                // 检查父目录是否存在，如果不存在，则创建它
                if (parentDir != null && !Files.exists(parentDir)) {
                    try {
                        // 创建目录，包括所有必需的父目录
                        Files.createDirectories(parentDir);
                        System.out.println("目录已创建: " + parentDir);
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("创建目录失败");
                    }
                }

                //-----------
                Files.write(path, bytes);
                fileNames.add(file.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传成功的文件: " + fileNames.toString();
    }
}
